<template>
  <div class="device-socket-server">
    <div class="socket-client-list">
      <div class="server-port">
        <el-input
            v-model="ServerInfo.Port" style="margin-right: 5px;margin-left: 10px" placeholder="请输入端口" size="small">
          <template #prepend>端口</template>
        </el-input>
        <!--        <el-input-->
        <!--            v-model="ServerInfo.Rerminator" style="margin-left: 5px;margin-right: 10px" size="small"-->
        <!--            placeholder="请输入结束符">-->
        <!--          <template #prepend>结束符</template>-->
        <!--        </el-input>-->
      </div>
      <div class="client-list">
        <div :class="[CurrentIndex===index?'client-item-selected':'','client-item']"
             v-for="(socket,index) in ConnectedClients"
             :key="socket"
             @click="SelectSocketClient(socket,index)">
          <div class="client-item-avatar">
            {{ index }}
          </div>
          <div class="client-item-ip">
            192.16.8.6
          </div>
        </div>
      </div>
      <div class="server-btns">
        <el-input v-model="ServerInfo.DeviceName" placeholder="请输入名称" size="small"/>
        <el-button type="success" :icon="Check" @click="SaveBtn" size="small" style="margin-left: 10px">保存</el-button>
        <el-button type="danger" :icon="Delete" @click="DeleteBtn" size="small">删除</el-button>
      </div>
    </div>
    <div class="socket-client-body">
      <div class="socket-message" ref="messageContainer">
        <div v-for="(MessageItem,index) in MessageList" :key="index"
             :class="[MessageItem.Send?'message-send':'','socket-message-item']">
          <span v-if="MessageItem.Send">
            <el-tag type="primary">{{ MessageItem.Data }}</el-tag>
            {{ MessageItem.Date }}
          </span>
          <span v-else>{{ MessageItem.Date }} <el-tag type="warning">{{ MessageItem.Data }}</el-tag></span>
        </div>
      </div>
      <div class="socket-send">
        <el-input v-model="SendMessage" placeholder="请输入要发送的消息" size="small"/>
        <el-button @click="SendMessageBtn" size="small" style="margin-left: 10px">发送</el-button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">

import {nextTick, onMounted, ref} from "vue";
import {Check, Delete} from "@element-plus/icons-vue";
//@ts-ignore
import SysDriveApi from "@/api/flow/SysDriveApi.js";
import {MessageSuccess, MessageError} from "@/utils";
import {ElMessageBox} from "element-plus";
//@ts-ignore
import {Emitter} from "@/utils/Emitter.js";
import {AppParams} from "@/utils/appParams";
//@ts-ignore
import Utils from "@/vue2-flow/src/utils/Common.js";
import {Device} from "@/api/DeviceApi";

const Emits = defineEmits(['close'])
const count = ref(0)
const ServerInfo = ref({
  Id: 0,
  DeviceName: '',
  Port: 6677,
  Rerminator: null,
  ServerEnable: false,
  DeviceType: 'SOCKET_SERVER'
})
const SendMessage = ref('')

const CurrentIndex = ref(0)
const ConnectedClients = ref([])
const CurrentInstance = ref()

const MessageList = ref<object[]>([])
const load = () => {
  count.value += 2
}

const DEVICE_LOGGER = (res: any) => {
  if (res.Type === 'SOCKET_SERVER' && res.DeiverInstance.Id === ServerInfo.value.Id && res.MessageStatus === 'RECEIVING_DATA') {
    res.Date = Utils.dateFormatStr(new Date(res.Date))
    MessageList.value.push(res)
    scrollToBottom()
  }
}

onMounted(() => {
  Emitter.on(AppParams.JAVA_SCRIPT_EVENT.DEVICE_LOGGER, DEVICE_LOGGER)
})

/**
 * 选中的客户端
 * @param Instance
 * @param Index
 * @constructor
 */
const SelectSocketClient = (Instance: object, Index: number) => {
  CurrentIndex.value = Index;
  CurrentInstance.value = Instance;
}

const SaveBtn = () => {
  const SI = ServerInfo.value
  new SysDriveApi().AddDrive(SI, (res: any) => {
    MessageSuccess('保存成功')
  })
}

const DeleteBtn = () => {
  const SI = ServerInfo.value
  ElMessageBox.confirm(
      `是否删除设备${SI.DeviceName}？`,
      '确认删除设备',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    new SysDriveApi().DeleteDevice(SI.Id, (de: any) => {
      if (de) {
        MessageSuccess('删除成功')
        Emits('close');
      }
    })
  })
}

const SendMessageBtn = () => {
  const SI = ServerInfo.value
  new SysDriveApi().SendMessage(SI.Id, CurrentIndex.value, SendMessage.value, (de: any) => {
    MessageList.value.push({Send: true, Data: SendMessage.value, Date: Utils.dateFormatStr()})
    scrollToBottom()
    if (!de) {
      MessageError('发送失败')
    }
  })
}

const LoadConnectedClients = () => {
  const SI = ServerInfo.value
  Device.GetSocketConnectedClients(SI.Id).then(res => {
    ConnectedClients.value = res.Data;
  })
}
const _Show = (Device: any) => {
  ServerInfo.value = Device
  LoadConnectedClients()
}
const messageContainer = ref<HTMLDivElement | null>(null)
// 滚动到底部的通用方法
const scrollToBottom = () => {
  nextTick(() => {
    messageContainer.value!.scrollTop = messageContainer.value?.scrollHeight || 0;
  });
}
defineExpose({_Show})
</script>

<style scoped lang="scss">
.device-socket-server {
  display: flex;
  flex-direction: row;
  height: 550px;

  .socket-client-list {
    background-color: #EFEFEF;
    display: flex;
    flex-direction: column;

    .server-port {
      display: flex;
      margin-top: 4px;

      .el-switch {
        padding: 0 6px;
      }
    }

    .client-list {
      flex: 1;


      .client-item-selected {
        background-color: #E6A23C;
        color: #fff;
        border-radius: 4px;
      }

      .client-item {
        display: flex;
        margin: 6px;
        align-items: center;
        cursor: pointer;

        .client-item-avatar {
          width: 50px;
          line-height: 50px;
          background-color: #c8c8c8;
          border-radius: 4px;
          text-align: center;
        }

        .client-item-ip {
          font-weight: 600;
          margin-left: 10px;
        }
      }
    }

    .server-btns {
      display: flex;
      padding: 10px 0;
      background-color: #fff;
      padding-right: 10px;
    }
  }

  .socket-client-body {
    display: flex;
    flex-direction: column;
    flex: 1;

    .socket-message {
      background-color: #F4F4F4;
      flex: 1;
      overflow-x: auto;
      width: 700px;

      .socket-message-item {
        padding-left: 10px;

        span {
          font-size: 12px;
        }
      }

      .message-send {
        display: flex;
        justify-content: end;
        padding-right: 10px;
      }
    }

    .socket-send {
      display: flex;
      justify-content: end;
      padding: 10px 0;

      > div:nth-child(1) {
        margin-left: 10px;
      }

      button {
        width: 110px;
      }
    }
  }
}
</style>
